package com.util;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.pojo.User;
import com.pojo.VerifyUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class TokenUtil {
    // 私钥设置
    public static final String TOKEN_SECRET = "6gahgadg80asd";
    public static final Map<String,Object> Token_User = new HashMap<>();

    /***
     * 生成Token
     */
    public static String getToken(VerifyUser verifyUser){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND,1800);//1800
        //创建payload的私有声明
        Map<String, Object> claims = new HashMap<>();
        claims.put("userInfo", JSON.toJSONString(verifyUser));
        JwtBuilder jwtBuilder = Jwts.builder()
                .setClaims(claims)
                .setExpiration(calendar.getTime())
                .signWith(SignatureAlgorithm.HS256, TOKEN_SECRET);
        String token = jwtBuilder.compact();
        Token_User.put(token,verifyUser);
        return token;
    }

    /***
     * 校验Token
     */
    public static boolean verify(String tokenToBeVerify){
        Claims claims = null;
        boolean flag=true;
        try {
            claims = Jwts.parser()
                    .setSigningKey(TOKEN_SECRET)
                    .parseClaimsJws(tokenToBeVerify).getBody();
        } catch (SignatureVerificationException e){
            flag=false;
            System.out.println(("--> 签名不一致 <--"));
        } catch (TokenExpiredException e){
            flag=false;
            System.out.println(("--> 令牌过期 <--"));
        } catch (AlgorithmMismatchException e){
            flag=false;
            System.out.println(("--> 签名算法不匹配 <--"));
        } catch (Exception e){
            flag=false;
            System.out.println(("--> 校验失败 <--"));
        }
        if(flag)
        System.out.println(("[info]jwt校验成功"));
        return flag;
    }
    /***
     *  根据token返回一个实体类
     */
    public static VerifyUser get(String token){
         return (VerifyUser) Token_User.get(token);
    }

}
